<?php
	require_once "functions.php";
	require_once "user.php";
	require_once "checklist.php";

	session_start();
	if(!$_SESSION['email'])
	   header('location /labua');
	else{
		$user = new user($_SESSION['email']);
	}
    	
	$con = getdb();

    $url = $_POST['url'];
    // checklist constructor
    $checklist = new checklist(NULL, $user->id, $url);
    $answers = $_POST["question"];
	$total_short = 0;
	$total_usability = 0;
	$snippet = "INSERT INTO answers (checklist_id, answer_number, score, comments) VALUES ";
	$i = 0;
	$max_score_short = 125;
	$max_score_usability = 50;

    foreach ($answers as $question => $value){

		if ( ($question > 0 ) && ($question < 26) ){
			$total_short += $value[0];
			if ($value[0] == 0){
				$max_score_short -= 5;
			}
		}
		else if ($question > 25 ){
			$total_usability += $value[0];
			if ($value[0] == 0){
				$max_score_usability -= 5;
			}
		}

		$snippet .= "(".$checklist->id.", ".$question.", ".$value[0].",' ".$_POST['comments'][$question][0]." ')";
		if ($i < count($answers) - 1){
			$snippet .= ", ";
		}
		$i++;
    }

    $con = getdb();
	$result = pg_query($con, $snippet);

	$checklist->setShortChecklistRating($total_short*10/$max_score_short);
	$checklist->setUsabilityChecklistRating($total_usability*10/$max_score_usability);
	if(!$result){
		header("Location: /savua");
	}
	else{
		pg_query($con, "COMMIT");
		pg_close($con);
		session_start();
		// $_SESSION["nota"] = $total*10/$max_score;
		$_SESSION["url"] = $checklist->url;
		header("Location: /savua/resultado.php?cid=".$checklist->id."");
	}

	pg_close($con);
?>